package com.example.counter.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.counter.feign.OrderService;
import com.example.counter.feign.vo.OrderMainVo;
import com.example.counter.mapper.PubStockMapper;
import com.example.counter.model.PubStock;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @ClassName PubStockServiceImpl.java
 * @Author 江南小俊
 * @Version 1.0.0
 * @Description TODO
 * @Date 2021/03/25 23:36:00
 */
@Service
@Slf4j
public class PubStockServiceImpl extends ServiceImpl<PubStockMapper, PubStock> {
    @Autowired
    private OrderService orderService;

    /**
     * @param orderNo
     * @return void
     * @description 扣减库存、修改订单状态
     * @date 2021/3/26 23:36
     * @author Jim
     **/

    @Transactional
    @GlobalTransactional
    public void orderDeductionOfInventory(Long orderNo) {
        log.info("xid:{},orderNo:{}", RootContext.getXID(), orderNo);
        //修改订单状态
        OrderMainVo orderMainVo = orderService.confirmOrder(orderNo);
        if (orderNo == 202103241154L) {
            throw new RuntimeException("模拟异常");
        }
        orderMainVo.getOrderDetailList().forEach(orderDetail -> {
            QueryWrapper<PubStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_id", orderDetail.getGoodsId());
            PubStock pubStock = getOne(queryWrapper);

            if (pubStock.getStockNum() < orderDetail.getGoodsNum()) {
                throw new RuntimeException("商品" + pubStock.getGoodsId() + "库存剩余库存数" + pubStock.getStockNum() + "小于购买商品数量" + orderDetail.getGoodsNum());
            } else {
                log.info("库存扣减前:{}", pubStock);
                pubStock.setStockNum(pubStock.getStockNum() - orderDetail.getGoodsNum());
                log.info("库存扣减后:{}", pubStock);
                updateById(pubStock);
            }
        });


    }
}
